import BaseView from "../../../Script/Base/BaseView";
import { EBundleType, EViewType } from "../../../Script/Common/Enum";
import { GlobalData } from "../../../Script/Common/GlobalData";
import { ETalkType, ISayConfig, TalkModule } from "../../../Script/Common/TalkModule";
import { IGameData, ITalkData, IViewData } from "../../../Script/Interface/IMessage";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import GameUI from "../GameUI";
import HomeUI from "../home/HomeUI";
import TownUI from "../town/TownUI";
import ItemChat from "./ItemChat";
import ItemName from "./ItemName";

const { ccclass, property } = cc._decorator;

export interface IShowDatas {
    /** 对话数据的id */
    chatId: number;
    /** 展示红点提示? */
    isPoint: boolean;
    /** 名字 */
    names: string[];
    /** 对话记录 */
    datas: IShowItem[],
}

export interface IShowItem {
    talkId: number;
    name: string;
    chat: string;
}

export interface IChatData {
    id: number;
    type: number;   // -1.自己 0.其他 ...
    chat: string;
    select?: {
        a: string;
        b: string;
    };
}

const VIEW_DATA: IViewData = {
    name: 'ChatUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

@ccclass
export default class ChatUI extends BaseView {
    public static instance: ChatUI = null;

    @property({ type: cc.Prefab, tooltip: "展示页item" })
    private itemShow: cc.Prefab = null;
    @property({ type: cc.Prefab, tooltip: "聊天页item" })
    private itemChat: cc.Prefab = null;

    @property({ type: cc.ScrollView, tooltip: "滑动框--名字页" })
    private scrollName: cc.ScrollView = null;
    @property({ type: cc.ScrollView, tooltip: "滑动框--聊天页" })
    private scrollChat: cc.ScrollView = null;

    @property({ type: cc.Node, tooltip: "展示页content" })
    private shows: cc.Node = null;
    @property({ type: cc.Node, tooltip: "聊天页content" })
    private chats: cc.Node = null;

    @property({ type: cc.Node, tooltip: "底部-对话内容按钮" })
    private btnSay: cc.Node = null;
    @property({ type: cc.Node, tooltip: "底部-结束对话按钮" })
    private btnOver: cc.Node = null;

    @property({ type: cc.Label, tooltip: "标题" })
    private labTitle: cc.Label = null;

    private showNodes: cc.Node[] = [];
    private chatNodes: cc.Node[] = [];

    public showDatas: IShowDatas[] = [];

    private gameData: IGameData = null;
    private talkData: ITalkData = null;

    // 当前点的id
    public clickID: number = 1001;

    protected onLoad() {
        super.onLoad();
        ChatUI.instance = this;

        this.gameData = StorageUtil.instance.getGameData();
        this.talkData = StorageUtil.instance.getTalkData();

        this.adaper();
        this.showNamePage();
    }

    protected adaper() {
        super.adaper();
        
        // 滑动区域高度减少
        if (GlobalData.fixType === '宽适配') {
            this.scrollName.node.height = this.shows.parent.height = 1300 - (GlobalData.design_height - GlobalData.stage_height);
            this.scrollChat.node.height = this.chats.parent.height = 1300 - (GlobalData.design_height - GlobalData.stage_height);
        }

        // console.log(this.scrollName.node.height, this.scrollChat.node.height, GlobalData.design_height, GlobalData.stage_height);
    }

    /**
     * 显示红点提示
     * @param show 
     * @param _talkData 
     * @param isNew 新对话?
     */
    public showRedPoint(show: IShowDatas) {
        if (show?.datas.length > 0) {
            const last = show.datas.length - 1;
            if (show.datas[last].name !== '顾云泽' && show.datas[last].talkId === this.talkData.id) {
                show.isPoint = true;
            } else {
                show.isPoint = false;
            }
        }
    }

    private setOneData(_talkData: ISayConfig) {
        let callback = (data: IShowDatas, isNew: boolean) => {
            const has = data.names.find((name) => name === _talkData.name);
            if (!has) {
                if (_talkData.isGroup) {
                    data.names.push(_talkData.name);
                } else {
                    if (_talkData.name !== "顾云泽") {
                        data.names.push(_talkData.name);
                    }
                }
            }
        }
        const show = this.showDatas.find((o1) => o1.chatId === _talkData.chatId);
        if (show) {
            callback && callback(show, false);
            show.datas.push({ talkId: _talkData.id, name: _talkData.name, chat: _talkData.desc });
            // 小红点提示
            this.showRedPoint(show);
        } else {
            const temp: IShowDatas = { chatId: _talkData.chatId, names: [], datas: [], isPoint: false };
            callback && callback(temp, true);
            temp.datas.push({ talkId: _talkData.id, name: _talkData.name, chat: _talkData.desc });
            this.showDatas.push(temp);
            // 小红点提示
            this.showRedPoint(temp);
        }
        callback = null;
    }

    private setSayDatas() {
        this.btnSay.active = false;
        this.btnOver.active = false;
        const old = TalkModule.getSayConfigById(this.talkData.id);
        if (old?.nextId) {
            this.talkData.id = old.nextId;
            const now = TalkModule.getSayConfigById(this.talkData.id);
            if (now) {
                // 设置一条数据
                this.setOneData(now);
                // console.log("this.showDatas:", this.showDatas);

                const showData = this.showDatas.find((o) => o.chatId === now.chatId);
                const temp = showData.datas[showData.datas.length - 1];
                this.addOneChat(temp);
            }
        } else {
            console.log("数据不存在||没有下条数据");
        }
    }

    private refreshUI(isNamePage: boolean) {
        if (isNamePage) {
            this.labTitle.string = '聊天';
        }
        this.btnSay.active = false;
        this.btnOver.active = false;
        this.isHasChild = !isNamePage;
        this.scrollName.node.active = isNamePage;
        this.scrollChat.node.active = !isNamePage;
        this.bottom.active = this.scrollChat.node.active;// 没有nextid出现bottom
    }

    private showNamePage() {
        this.refreshUI(true);

        this.showDatas = [];
        for (let i = this.showNodes.length - 1; i > -1; i--) {
            this.showNodes[i].destroy();
        }
        this.showNodes = [];

        const tempDatas = TalkModule.getChatConfigByType(ETalkType.Chat);
        // console.log("tempDatas:", tempDatas);
        tempDatas.forEach((o, i) => {
            this.setOneData(o);
        });
        // console.log("showDatas:", this.showDatas);

        this.showDatas.forEach((o) => {
            const item = cc.instantiate(this.itemShow);
            item.parent = this.shows;
            item.getComponent(ItemName).setData(o);
            this.showNodes.push(item);
        });
    }

    public showChatPage(showData: IShowDatas, init: boolean = true) {
        this.refreshUI(false);
        for (let i = this.chatNodes.length - 1; i > -1; i--) {
            this.chatNodes[i].destroy();
        }
        this.chatNodes = [];

        for (let i = 0; i < showData.datas.length; i++) {
            const temp = showData.datas[i];
            this.addOneChat(temp);
        }
        const name = this.getNameString(showData.names);
        this.labTitle.string = `${name}`;
        if (init) {
            this.scrollChat.scrollToTop();
            this.scrollChat.scrollToBottom(0.5);
        }
    }

    private addOneChat(data: IShowItem) {
        const item = cc.instantiate(this.itemChat);
        // setTimeout(() => {
        item.parent = this.chats;
        item.getComponent(ItemChat).setData(data);
        this.chatNodes.push(item);
        this.scrollChat.scrollToBottom(0.3);
        // }, 100);
    }

    /** 刷新底部ui */
    public async refreshTalk() {
        this.btnSay.active = false;
        this.btnOver.active = false;
        const old = TalkModule.getSayConfigById(this.talkData.id);
        if (old?.nextId && this.clickID === old.chatId) {
            const now = TalkModule.getSayConfigById(old.nextId);
            if (now.type === ETalkType.Chat) {
                if (now.name === '顾云泽') {
                    this.btnSay.active = true;
                    const labSay = cc.find('say', this.btnSay).getComponent(cc.Label);
                    labSay.string = GameUtil.truncateString(now.desc, 12);
                } else {
                    await GameUtil.sleep(GlobalData.isFast ? 100 : 500);
                    this.setSayDatas();
                }
                // this.talkData.id = now.id;
                console.log("ChatUI.refreshTalk()===>当前id:", now.id);
            }
        } else {
            this.btnOver.active = true;
        }
    }

    public getNameString(names: string[]) {
        let str = '';
        if (names.length > 2) {
            names.forEach((o, i) => {
                str += i == 0 ? o : ("、" + o);
            });
            str = GameUtil.truncateString(str, 12);
        } else {
            str = GameUtil.truncateString(names[0], 12);
        }
        return str;
    }

    public getChatString(data: IShowItem[]) {
        const length = data.length;
        if (length > 0) {
            const chat = data[length - 1].chat;
            return GameUtil.truncateString(chat, 12);
        }
        return '';
    }

    private onBtnSayClicked(event: cc.Event.EventTouch, data: string) {
        this.btnSay.active = false;
        this.btnOver.active = false;
        this.setSayDatas();
    }

    public onCloseChild() {
        // TODO
        // 关闭时刷新，防止有连续对话
        // 聊天结束时，talkid手动+1，并刷新页面
        const arr = [10106, 10604, 10607, 10902, 11000, 11007, 11103, 11203,];
        for (let i = 0; i < arr.length; i++) {
            if (this.talkData.id === arr[i]) {
                this.talkData.id++;
            }
        }

        this.refreshUI(true);
        this.showNamePage();
    }

    public async onCloseClicked() {
        super.onCloseClicked();
        await GameUtil.sleep(500);
        HomeUI.instance?.check();
        TownUI.instance?.check();
        GameUI.instance?.check();
    }
}
AppService.instance.registViewData(VIEW_DATA);